<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1000">
    <ContentWrap>
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="选中联系人首个邮箱" prop="isSelectFirstMail">
          <el-checkbox
            v-model="filterParams.isSelectFirstMail"
            @change="handleIsSelectFirstMailChange"
          />
        </el-form-item>
        <el-form-item label="仅选中主联系人" prop="isOnlyMailContact">
          <el-checkbox
            v-model="filterParams.isOnlyMainContact"
            @change="handleIsOnlyMailContactChange"
          />
        </el-form-item>
        <el-form-item label="显示离职联系人" prop="isShowResignContact">
          <el-checkbox
            v-model="filterParams.isShowResignContact"
            @change="handleIsShowResignContactChange"
          />
        </el-form-item>
      </el-form>
      <div class="flex">
        <Table
          ref="tableRef"
          :columns="columns"
          :adaptive="true"
          :data="queryData"
          :row-style="rowStyle"
          @select="handleTableSelectChange"
          @select-all="handleTableSelectChange"
        />
        <div>
          <el-button
            size="small"
            circle
            style="margin-left: 16px; margin-top: 100px; margin-bottom: 170px"
            @click="handleAddReceivers"
          >
            <Icon class="ml-1" icon="ic:baseline-arrow-forward-ios" />
          </el-button>
          <el-button
            size="small"
            circle
            style="margin-left: 16px"
            @click="handleAddCarbonReceivers"
          >
            <Icon class="ml-1" icon="ic:baseline-arrow-forward-ios" />
          </el-button>
        </div>
        <div class="block">
          <el-scrollbar
            style="
              width: 300px;
              height: 200px;
              border: 1px solid #ebeef5;
              margin-left: 15px;
              margin-right: 20px;
              margin-bottom: 20px;
              padding: 8px;
            "
          >
            <div class="flex">
              <el-text class="font-bold">收件人（{{ selectReceivers.length }}）</el-text>
              <el-button
                class="ml-auto"
                size="small"
                text
                type="primary"
                @click="handleClearReceivers"
                >清空</el-button
              >
            </div>

            <div v-for="row in selectReceivers" :key="row.id" class="flex mt-3">
              <div
                style="
                  display: flex;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  width: 250px;
                "
                class="mr-2"
              >
                <span style="font-weight: bold"> {{ row.contact.name }}</span>
                <span>&lt;{{ row.mailAddress }}&gt;</span>
              </div>
              <el-button
                style="width: 15px; margin-left: auto"
                text
                size="small"
                @click="() => handleDeleteReceiver(row.id)"
              >
                <Icon icon="ep:delete" />
              </el-button>
            </div>
          </el-scrollbar>

          <el-scrollbar
            style="
              width: 300px;
              height: 200px;
              border: 1px solid #ebeef5;
              margin-left: 15px;
              margin-right: 20px;
              padding: 8px;
            "
          >
            <div class="flex">
              <el-text class="font-bold">抄送人（{{ selectCarbonReceivers.length }}）</el-text>
              <el-button
                class="ml-auto"
                size="small"
                text
                type="primary"
                @click="handleClearCarbonReceivers"
                >清空</el-button
              >
            </div>
            <div v-for="row in selectCarbonReceivers" :key="row.id" class="flex mt-3">
              <div
                style="
                  display: flex;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  width: 250px;
                "
                class="mr-2"
              >
                <span style="font-weight: bold"> {{ row.contact.name }}</span>
                <span>&lt;{{ row.mailAddress }}&gt;</span>
              </div>
              <el-button
                style="width: 15px; margin-left: auto"
                text
                size="small"
                @click="() => handleDeleteCarbonReceiver(row)"
              >
                <Icon icon="ep:delete" />
              </el-button>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </ContentWrap>
    <template #footer>
      <el-button type="primary" @click="handleClickSendMail">发邮件</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="CustomerSendMailSelect" lang="ts">
import * as BusinessFieldApi from '@/api/setting/businessField'
const { push } = useRouter() // 路由
const message = useMessage() // 消息弹窗
const selectCount = ref(0)
const dialogTitle = ref('')
const dialogVisible = ref(false)
const queryData = ref()
const queryFormRef = ref()
const queryParams = ref({})
const resignOptionId = ref()
const tableRef = ref()
const selectReceivers = ref<any[]>([])
const selectCarbonReceivers = ref<any[]>([])
const filterParams = ref({
  isIndeterminate: false,
  isSelectFirstMail: true,
  isOnlyMainContact: true,
  isShowResignContact: false
})
const columns = [
  {
    type: 'selection',
    align: 'center'
  },
  {
    label: '邮件地址',
    prop: 'mailAddress',
    formatter: (row) => row.contact.name + '<' + row.mailAddress + '>'
  },
  {
    label: '职位',
    prop: 'contact.position'
  },
  {
    label: '客户',
    prop: 'contact.customer.name'
  }
]
/** 打开弹窗 */
const open = async ({ customerName, mailInfos }) => {
  dialogVisible.value = true
  resetForm()
  dialogTitle.value = '给' + customerName + '发邮件'
  resignOptionId.value = await BusinessFieldApi.getWorkStateResignOptionId()
  queryData.value = mailInfos
  showMailInfo()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const showMailInfo = () => {
  setTimeout(() => {
    setTableSelect(true, true)
  }, 10)
}

const handleIsSelectFirstMailChange = (isSelectFirstMail) => {
  setTableSelect(isSelectFirstMail, filterParams.value.isOnlyMainContact)
}

const handleIsOnlyMailContactChange = (isOnlyMailContact) => {
  setTableSelect(filterParams.value.isSelectFirstMail, isOnlyMailContact)
}

const handleIsShowResignContactChange = (isShowResignContact) => {
  if (!isShowResignContact) {
    queryData.value.forEach((data) => {
      if (data.contact.workState == resignOptionId.value) {
        tableRef.value.getTableRef().toggleRowSelection(data, false)
      }
    })
  }
}

const rowStyle = ({ row }) => {
  if (row?.contact.workState == resignOptionId.value && !filterParams.value.isShowResignContact) {
    return { display: 'none' }
  } else return {}
}

const setTableSelect = (isSelectFirstMail, isOnlyMainContact) => {
  let lastContactId = 0
  tableRef.value.getTableRef().data.forEach((row) => {
    if (!filterParams.value.isShowResignContact && row.contact.workState == resignOptionId.value)
      return
    if (
      ((isSelectFirstMail && lastContactId != row.contact.id) || !isSelectFirstMail) &&
      ((isOnlyMainContact && row.contact.isMain) || !isOnlyMainContact)
    )
      tableRef.value.getTableRef().toggleRowSelection(row, true)
    else tableRef.value.getTableRef().toggleRowSelection(row, false)
    lastContactId = row.contact.id
  })
  selectCount.value = tableRef.value.getTableRef().getSelectionRows().length
}

const handleTableSelectChange = () => {
  filterParams.value.isOnlyMainContact = false
  filterParams.value.isSelectFirstMail = false
}

const resetForm = () => {
  selectReceivers.value = []
  selectCarbonReceivers.value = []
  filterParams.value = {
    isIndeterminate: false,
    isSelectFirstMail: true,
    isOnlyMainContact: true,
    isShowResignContact: false
  }
}

/** 提交表单 */
const handleClickSendMail = async () => {
  if (selectReceivers.value.length == 0 && selectCarbonReceivers.value.length == 0) {
    await message.confirm('没有选择收件人和抄送人，确定继续吗?')
  }
  dialogVisible.value = false
  const receivers = selectReceivers.value.map((receiver) => {
    return { name: receiver.contact.name, address: receiver.mailAddress }
  })
  const carbonReceivers = selectCarbonReceivers.value.map((receiver) => {
    return { name: receiver.contact.name, address: receiver.mailAddress }
  })
  push({
    name: 'MailEdit',
    state: {
      receivers: receivers,
      carbonReceivers: carbonReceivers,
      type: 'customerSend'
    }
  })
}

const handleAddReceivers = () => {
  tableRef.value
    .getTableRef()
    .getSelectionRows()
    .forEach((row) => {
      if (!filterParams.value.isShowResignContact && row.contact.workState == resignOptionId.value)
        return
      const index = selectReceivers.value.indexOf(row)
      if (index < 0) {
        selectReceivers.value.push(row)
      }
    })
}

const handleAddCarbonReceivers = () => {
  tableRef.value
    .getTableRef()
    .getSelectionRows()
    .forEach((row) => {
      if (!filterParams.value.isShowResignContact && row.contact.workState == resignOptionId.value)
        return
      const index = selectCarbonReceivers.value.indexOf(row)
      if (index < 0) {
        selectCarbonReceivers.value.push(row)
      }
    })
}

const handleDeleteReceiver = (row) => {
  const index = selectReceivers.value.indexOf(row)
  if (index >= 0) {
    selectReceivers.value.splice(index, 1)
  }
}

const handleDeleteCarbonReceiver = (row) => {
  const index = selectCarbonReceivers.value.indexOf(row)
  if (index >= 0) {
    selectCarbonReceivers.value.splice(index, 1)
  }
}

const handleClearReceivers = () => {
  selectReceivers.value = []
}

const handleClearCarbonReceivers = () => {
  selectCarbonReceivers.value = []
}
</script>
